<template>
  <view class="my-container">
    <!-- 用户信息区域 -->
    <view class="user-info-section" :style="userThemeStyle">
      <view class="user-info" v-if="isLogin">
        <image 
          class="avatar" 
          :src="userInfo.avatarUrl || '/static/default-avatar.png'" 
          mode="aspectFill"
          @error="handleAvatarError"
        ></image>
        <view class="user-detail">
          <text class="nickname">{{userInfo.nickname || '用户' + (userInfo.phone ? userInfo.phone.substr(-4) : '')}}</text>
          <view class="user-tags">
            <text class="role-tag">{{getRoleText(userInfo.role)}}</text>
             <text class="role-tag">{{getCertificationStatusText(this.teacherCertification.status)}}</text>
            <text class="vip-tag" v-if="userInfo.hy > 0" :class="{'svip': userInfo.hy === 2}" @click="goToMembership">
              {{getVipText(userInfo.hy)}}
            </text>
          </view>
        </view>
      </view>
      <view class="not-login" v-else @click="goLogin">
        <image class="default-avatar" src="/static/logo.png" mode="aspectFill"></image>
        <view class="login-tip">
          <text class="main-tip">立即登录</text>
          <text class="sub-tip">登录后查看更多信息</text>
        </view>
        <text class="arrow-right">></text>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-list">
      <view class="menu-item" @click="goToOrders">
        <text class="menu-title">我的订单</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" @click="goToCourse">
        <text class="menu-title">我的课程</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" v-if="userInfo.role === 2" @click="goToMyTeaching">
        <text class="menu-title">我的授课</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" v-if="userInfo.role === 2" @click="goToAvailableTime">
        <text class="menu-title">可授课日期</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" v-if="userInfo.role === 2 && teacherCertification.status === 1" @click="goToMyCourseSchedule">
        <text class="menu-title">我的排课</text>
        <text class="menu-arrow">></text>
      </view>
<!--      待后续完成-->
<!--      <view class="menu-item" @click="goToFavorites">-->
<!--        <text class="menu-title">我的收藏</text>-->
<!--        <text class="menu-arrow">></text>-->
<!--      </view>-->
      <view class="menu-item" @click="goToCoupons">
        <text class="menu-title">我的优惠券</text>
        <text class="menu-arrow">></text>
      </view>
      <!--      待后续完成-->
<!--      <view class="menu-item" @click="goToMember">-->
<!--        <text class="menu-title">会员中心</text>-->
<!--        <text class="menu-arrow">></text>-->
<!--      </view>-->
<!--      <view class="menu-item" @click="contactService">-->
<!--        <text class="menu-title">联系客服</text>-->
<!--        <text class="menu-arrow">></text>-->
<!--      </view>-->
      <view class="menu-item" @click="goToSettings">
        <text class="menu-title">设置</text>
        <text class="menu-arrow">></text>
      </view>
      <!--      待后续完成-->
<!--      <view class="menu-item" @click="goToMcpData">-->
<!--        <text class="menu-title">MCP数据智能助手</text>-->
<!--        <text class="menu-arrow">></text>-->
<!--      </view>-->
      <view class="menu-item" v-if="userInfo.hy > 0" @click="showThemeSelector">
        <text class="menu-title">主题颜色</text>
        <view class="theme-preview" :style="{ background: currentThemeColor }"></view>
        <text class="menu-arrow">></text>
      </view>
    </view>

    <!-- 主题颜色选择器弹窗 -->
    <view class="theme-selector" v-if="showThemePopup">
      <view class="theme-selector-mask" @click="hideThemeSelector"></view>
      <view class="theme-selector-content">
        <view class="theme-selector-header">
          <text class="theme-selector-title">选择主题色</text>
          <text class="theme-selector-close" @click="hideThemeSelector">×</text>
        </view>
        <view class="theme-color-list">
          <view 
            v-for="(color, index) in themeColors" 
            :key="index"
            class="theme-color-item"
            :class="{ active: currentThemeColor === color }"
            :style="{ background: color }"
            @click="selectThemeColor(color)"
          ></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {teacherApi, userApi} from '../../api'
import {getCertificationStatus} from "../../api/teacher";

export default {
  data() {
    return {
      isLogin: false,
      userInfo: {
        id: '',
        nickname: '',
        phone: '',
        avatarUrl: '/static/default-avatar.png',
        role: '',
        status: ''
      },
      teacherCertification:{},
      showThemePopup: false,
      currentThemeColor: '#4080FF',
      themeColors: [
        '#4080FF', // 默认蓝色
        '#FF6B6B', // 红色
        '#42B983', // 绿色
        '#FF9500', // 橙色
        '#9C27B0', // 紫色
        '#795548', // 棕色
        '#607D8B', // 蓝灰色
        '#E91E63'  // 粉色
      ]
    }
  },
  computed: {
    userThemeStyle() {
      return this.userInfo.hy > 0 ? { background: this.currentThemeColor } : {}
    }
  },
  onLoad() {
    // 页面加载时检查登录状态
    this.checkLoginAndGetUserInfo()
    
    // 监听登录状态变化
    uni.$on('loginStateChanged', this.handleLoginStateChanged)

    // 加载保存的主题颜色
    const savedTheme = uni.getStorageSync('userThemeColor')
    if (savedTheme) {
      this.currentThemeColor = savedTheme
    }
  },
  onShow() {
    // 每次显示页面时检查登录状态
    this.checkLoginAndGetUserInfo()
  },
  onUnload() {
    // 页面卸载时移除监听
    uni.$off('loginStateChanged', this.handleLoginStateChanged)
  },
  methods: {
    // 处理登录状态变化
    handleLoginStateChanged({ isLogin, userInfo }) {

      console.log('收到登录状态变化:', { isLogin, userInfo })
      this.isLogin = isLogin
      if (isLogin && userInfo) {
        this.userInfo = userInfo
      } else {
        this.userInfo = {
          id: '',
          nickname: '',
          phone: '',
          avatarUrl: '/static/default-avatar.png',
          role: '',
          status: ''
        }
      }
    },

    // 检查登录状态并获取用户信息
    async checkLoginAndGetUserInfo() {
      try {
        const app = getApp()
        // 检查登录状态标记
        const loginState = uni.getStorageSync('loginState')
        
        // 优先使用全局状态
        if (app.globalData.isLogin && app.globalData.userInfo) {
			
			console.log("customer-service:index"+"获取用户信息")
          this.isLogin = true
          this.userInfo = app.globalData.userInfo
          // 在后台更新最新用户信息
          this.getUserInfo()
          return
        }

        // 如果有登录状态标记，尝试恢复登录状态
        if (loginState === 'logged_in') {
          const userInfo = uni.getStorageSync('userInfo')
          if (userInfo && userInfo.id) {
            this.isLogin = true
            this.userInfo = userInfo
            // 更新全局状态
            app.updateLoginStatus(true, userInfo)
            // 在后台更新最新用户信息
            this.getUserInfo()
            return
          }
        }

        // 如果没有登录状态标记，检查是否有token和用户信息
        const accessToken = uni.getStorageSync('accessToken')
        const userInfo = uni.getStorageSync('userInfo')
        
        if (accessToken && userInfo && userInfo.id) {
          this.isLogin = true
          this.userInfo = userInfo
          // 更新全局状态和登录状态标记
          app.updateLoginStatus(true, userInfo)
          // 在后台更新最新用户信息
          this.getUserInfo()
        } else {
          this.clearLoginState()
        }
      } catch (error) {
        console.error('检查登录状态失败:', error)
        this.clearLoginState()
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const accessToken = uni.getStorageSync('accessToken')
        const userInfo = uni.getStorageSync('userInfo')
        
     
      //   const res = await new Promise((resolve, reject) => {
      //     uni.request({
      //       url: `user/info/${userInfo.id}`,
      //       method: 'GET',
      //       header: {
						// 	'Authorization': uni.getStorageSync('access_token')
						// },
      //       success: (response) => {
      //         resolve(response)
      //       },
      //       fail: (error) => {
      //         reject(error)
      //       }
      //     })
      //   })
		const res = await userApi.getUserInfo(userInfo.id)
	  

        console.log('获取用户信息结果:', res)

        if (res.code === 200) {
          console.log("判断是否进入入逻辑"+res.data);
          
          // 确保数据中包含所有必要的字段
          const userData = {
            id: res.data.id,
            nickname: res.data.nickname || '',
            phone: res.data.phone || '',
            avatarUrl: res.data.avatarUrl || '/static/default-avatar.png',
            role: res.data.role || '',
            status: res.data.status || '',
            hy: res.data.hy 
          }

          console.log('用户信息:', userData)
          // 如果用户的角色 是教师 --2，那么查询教师认证情况
          if (userData.role == 2){
              const statusres =await teacherApi.getCertificationStatus(userData.id)
              this.teacherCertification = statusres.data

              console.log('获取教师认证结果:', res)
              console.log('测试赋值:', this.teacherCertification)
          }


          this.userInfo = userData
          // 更新存储的用户信息和全局状态
          uni.setStorageSync('userInfo', userData)
          getApp().updateLoginStatus(true, userData)
        } else {
          throw new Error(res.data?.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        if (error.statusCode === 401) {
          this.clearLoginState()
        }
      }
    },

    // 清除登录状态
    clearLoginState() {
      console.log('清除登录状态')
      const app = getApp()
      this.isLogin = false
      this.userInfo = {
        id: '',
        nickname: '',
        phone: '',
        avatarUrl: '/static/default-avatar.png',
        role: '',
        status: '',
        hy: 0
      }
      // 清除所有登录相关信息
      uni.removeStorageSync('loginState')
      uni.removeStorageSync('accessToken')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
      app.updateLoginStatus(false)
    },

    // 跳转到登录页
    goLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    },

    // 获取角色文本
    getRoleText(role) {
      switch (role) {
        case 1:
          return '学生'
        case 2:
          return '老师'
        default:
          return '选择身份'
      }
    },
    getCertificationStatusText(status) {
      switch (status) {
        case 0:
          return '认证待审核'
        case 1:
          return '已通过认证'
        case 2:
          return '已驳回'
        default:
          return '未认证'
      }
    },

    // 获取会员文本
    getVipText(hy) {
      switch (hy) {
        case 1:
          return 'VIP会员'
        case 2:
          return 'SVIP会员'
        default:
          return '普通用户'
      }
    },

    // 以下是菜单项的跳转方法
    goToOrders() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/orders/list' })
    },

    goToCourse() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/my/mycourses' })
    },

    goToMyTeaching() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/my/teaching' })
    },

    goToAvailableTime() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/teacher/available-time' })
    },

    goToMyCourseSchedule() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/teacher/course-schedule' })
    },

    goToFavorites() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/favorites/list' })
    },

    goToCoupons() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/coupon/list' })
    },

    goToMember() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/my/membership/membership' })
    },

    contactService() {
      if (!this.isLogin) return this.goLogin()
      // 跳转到AI客服聊天页面
      uni.navigateTo({ url: '/pages/chat/index' })
    },

    goToSettings() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/settings/index' })
    },

    goToMcpData() {
      if (!this.isLogin) return this.goLogin()
      uni.navigateTo({ url: '/pages/mcp-database/index' })
    },

    // 处理头像加载错误
    handleAvatarError() {
      console.log('头像加载失败，使用默认头像')
      this.userInfo.avatarUrl = '/static/default-avatar.png'
    },

    showThemeSelector() {
      if (this.userInfo.hy > 0) {
        this.showThemePopup = true
      } else {
        uni.showToast({
          title: '开通VIP即可使用主题功能',
          icon: 'none'
        })
      }
    },

    hideThemeSelector() {
      this.showThemePopup = false
    },

    selectThemeColor(color) {
      this.currentThemeColor = color
      uni.setStorageSync('userThemeColor', color)
      this.hideThemeSelector()
      uni.showToast({
        title: '主题已更新',
        icon: 'success'
      })
    },

    // 跳转到会员信息页面
    goToMembership() {
      if (!this.isLogin) return this.goLogin();
      uni.navigateTo({ url: '/pages/my/membership/membership' });
    }
  }
}
</script>

<style>
.my-container {
  min-height: 100vh;
  background: #f5f6fa;
}

.user-info-section {
  background: #4080FF;
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
}

.user-info, .not-login {
  display: flex;
  align-items: center;
}

.avatar, .default-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-detail {
  flex: 1;
}

.nickname {
  font-size: 36rpx;
  color: #fff;
  font-weight: 500;
  margin-bottom: 10rpx;
}

.user-tags {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-top: 10rpx;
}

.role-tag {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  background: rgba(255, 255, 255, 0.2);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.vip-tag {
  background-color: #FFB800;
  color: #ffffff;
  padding: 4rpx 12rpx;
  font-size: 20rpx;
  border-radius: 6rpx;
  margin-left: 10rpx;
  position: relative;
  overflow: hidden;
}

.vip-tag:active {
  opacity: 0.8;
}

.vip-tag::after {
  content: '';
  position: absolute;
  width: 30rpx;
  height: 200%;
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(30deg);
  top: -100%;
  left: -100%;
  transition: all 0.3s;
}

.vip-tag:active::after {
  left: 120%;
}

.vip-tag.svip {
  color: #FF4500;
  background: rgba(255, 69, 0, 0.2);
}

.phone {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.not-login {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
}

.login-tip {
  flex: 1;
}

.main-tip {
  font-size: 36rpx;
  color: #fff;
  font-weight: 500;
  margin-bottom: 10rpx;
  display: block;
}

.sub-tip {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.arrow-right {
  color: #fff;
  font-size: 32rpx;
  margin-left: 20rpx;
}

.menu-list {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-title {
  font-size: 32rpx;
  color: #333;
}

.menu-arrow {
  color: #999;
  font-size: 32rpx;
}

.theme-preview {
  width: 40rpx;
  height: 40rpx;
  border-radius: 20rpx;
  margin-right: 20rpx;
}

.theme-selector {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.theme-selector-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.theme-selector-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;
}

.theme-selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.theme-selector-title {
  font-size: 32rpx;
  font-weight: bold;
}

.theme-selector-close {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

.theme-color-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 20rpx 0 40rpx;
}

.theme-color-item {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  border: 4rpx solid transparent;
}

.theme-color-item.active {
  border-color: #333;
  transform: scale(1.1);
}
</style> 
